<template>
  <div class="category-page">
    <front-header></front-header>
    <div class="main-content">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>{{ categoryName }}</h2>
        <div class="total-count">共 {{ total }} 件商品</div>
      </div>

      <!-- 排序和搜索区域 -->
      <div class="toolbar">
        <div class="sort-options">
          <el-radio-group v-model="sortBy" size="small" @change="handleSort">
            <el-radio-button label="default">默认排序</el-radio-button>
            <el-radio-button label="sales,desc">销量优先</el-radio-button>
            <el-radio-button label="price,asc">价格从低到高</el-radio-button>
            <el-radio-button label="price,desc">价格从高到低</el-radio-button>
          </el-radio-group>
        </div>
        <div class="search-box">
          <el-input v-model="searchKey" placeholder="搜索商品" prefix-icon="el-icon-search" clearable></el-input>
        </div>
      </div>

      <!-- 商品列表 -->
      <div class="products-grid" v-loading="loading">
        <el-empty v-if="!loading && products.length === 0" description="暂无商品">
          <el-button type="success" @click="$router.push('/products')">查看全部商品</el-button>
        </el-empty>

        <el-row :gutter="20" v-else>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="product in products" :key="product.id" class="product-col">
            <product-card :product="product" />
          </el-col>
        </el-row>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="total > 0">
        <el-pagination background :current-page.sync="currentPage" :page-size="pageSize" :total="total" layout="prev, pager, next, jumper"
          @current-change="getProducts">
        </el-pagination>
      </div>
    </div>
    <front-footer></front-footer>
  </div>
</template>

<script>
import FrontHeader from '@/components/front/FrontHeader.vue'
import FrontFooter from '@/components/front/FrontFooter.vue'
import ProductCard from '@/components/front/ProductCard.vue'
import Request from '@/utils/request'
import { debounce } from 'lodash'

export default {
  name: 'Category',
  components: {
    FrontHeader,
    FrontFooter,
    ProductCard
  },
  data() {
    return {
      userInfo: JSON.parse(localStorage.getItem('frontUser') || '{}'),
      loading: false,
      products: [],
      categoryName: '',
      currentPage: 1,
      pageSize: 12,
      total: 0,
      sortBy: 'default',
      searchKey: '',
      debouncedSearch: null
    }
  },
  created() {
    this.userInfo = JSON.parse(localStorage.getItem('frontUser') || '{}')
    this.categoryName = this.$route.query.name || '分类商品'
    this.debouncedSearch = debounce(() => {
      this.currentPage = 1
      this.getProducts()
    }, 300)
    this.getProducts()
  },
  watch: {
    searchKey() {
      this.debouncedSearch()
    }
  },
  methods: {
    async getProducts() {
      this.loading = true
      try {
        const params = {
          categoryId: this.$route.params.id,
          status: 1,
          currentPage: this.currentPage,
          size: this.pageSize,
          name: this.searchKey || undefined
        }

        if (this.sortBy && this.sortBy !== 'default') {
          const [field, order] = this.sortBy.split(',')
          params.sortField = field
          params.sortOrder = order
        }

        const res = await Request.get('/product/page', { params })
        if (res.code === '0') {
          if (res.data && res.data.records) {
            this.products = res.data.records.map(product => ({
              ...product,
              isFavorite: false,
              imageUrl: product.imageUrl?.startsWith('http') ? product.imageUrl : `${product.imageUrl}`
            }))
            this.total = res.data.total
           
          } else {
            this.products = []
            
            this.total = 0
          }
        } else {
          this.products = []
          this.total = 0
          this.$message.error(res.msg || '获取商品列表失败')
        }
        this.loading = false
      } catch (error) {
        console.error('获取商品列表失败:', error)
        this.$message.error('获取商品列表失败')
        this.products = []
        this.total = 0
      }
    },

    handleSort() {
      this.currentPage = 1
      this.getProducts()
    },
    isLogin() {
      if (!this.userInfo?.id) {
        this.$message.warning('请先登录')
        this.$router.push('/login')
        return false
      }
      return true
    },
 
  }
}
</script>

<style scoped>
.category-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f9f9f9;
  color: #333;
}

.main-content {
  flex: 1;
  max-width: 1200px;
  margin: 40px auto;
  padding: 0 20px;
  width: 100%;
  box-sizing: border-box;
  max-height: 100%;
  overflow: auto;
}

/* 页面标题样式 */
.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30px;
  background: #fff;
  padding: 20px 30px;
  border-radius: 12px;
  box-shadow: 0 3px 15px rgba(0, 0, 0, 0.05);
  border: 1px solid #f0f0f0;
}

.page-header h2 {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0;
  position: relative;
  display: inline-block;
}

.page-header h2::after {
  content: "";
  position: absolute;
  bottom: -4px;
  left: 0;
  width: 40px;
  height: 3px;
  background: linear-gradient(90deg, #4caf50, #81c784);
  border-radius: 2px;
}

.total-count {
  font-size: 14px;
  color: #666;
  background: #f5f5f5;
  padding: 6px 12px;
  border-radius: 20px;
}

/* 排序和搜索区域 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  background: #fff;
  padding: 15px 20px;
  border-radius: 12px;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.03);
}

.search-box {
  width: 250px;
}

/* 商品列表 */
.products-grid {
  margin-bottom: 40px;
  min-height: 400px;
}

.product-col {
  margin-bottom: 25px;
}

/* 分页 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin: 30px 0 50px;
}

/* 响应式布局 */
@media (max-width: 992px) {
  .main-content {
    margin: 30px auto;
  }
}

@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .search-box {
    width: 100%;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
    padding: 15px 20px;
  }
  
  .total-count {
    align-self: flex-start;
  }
}

@media (max-width: 576px) {
  .main-content {
    padding: 0 15px;
    margin: 20px auto;
  }
  
  .page-header h2 {
    font-size: 20px;
  }
}
</style> 